class User < ApplicationRecord
	validates :name, length: { maximum: 15 }
	validates :mobile, presence: true, uniqueness: true, length: { maximum: 50 }
  validates :password, presence: true, length: { minimum: 6 }
	has_secure_password

  has_many :employees

  class << self
    def mobile_with(mobile)
      unscoped.where('mobile = ?', mobile).first
    end
  end


  #判断用户是否为公司主理人
  def owner?
    @company = Company.find(self.last_company_id)
    @company && @company.owner_id==self.id
  end

  #产品总监
  def product_director?
    self.owner? && 1==1
  end

  #人资总监
  def hr_director?
    # self.owner? && 1==1
    false
  end


  #根据角色权限验证 flydragon
  def authorize_by_role?(role)

    p "验证角色为:#{role},用户拥有角色为:#{roles.join(',')}"
    roles.include?("all") || roles.include?(role)
  end

  #获取当前用户的角色 flydragon
  def roles

    roles = []
    # if PositionConfiguration.default_position?()
    #获取当前用户的员工
    Employee.where({:user_id => self.id,:company_id => self.last_company_id}).map{|employee|
      employee.employee_of_studios.map{|employee_of_studio|
        
        position_name = employee_of_studio.position_name
        if PositionConfiguration.default_position?(position_name)
          roles += PositionConfiguration.get_default_positions_roles(position_name)
        else

          #获取自定义的权限，逻辑需要再次开发
          roles += []
        end
      }
    }
    roles
  end

  #更新当前用户的访问位置为公司  flydragon
  def scope_to_company
    UserService.new(self).reset_scope_to_company
  end

  #更新当前用户的访问位置到分店 flydragon
  def scope_to_studio
    UserService.new(self).reset_scope_to_studio
  end

  #当前用户的访问位置是否在公司 flydragon
  def scope_company?
    UserService.new(self).scope_to_company?
  end

  #获取用户的职务列表 flydragon
  def positions
    return @positions if @positions.present?
    @positions = [] 
    #获取当前用户的员工
    Employee.where({:user_id => self.id,:company_id => self.last_company_id}).each{|employee|
      employee.employee_of_studios.each{|employee_of_studio|
        @positions << employee_of_studio.position_name
      }
    }
    @positions
  end

  #检测用户是否为特定职务 flydragon
  def is_position?(position_name)
    positions.include?(position_name)
  end

  #检测用户是否为单纯的前台职务
  def is_receptionist?
    is_position?("前台") && !is_position?("运营总监")
  end



end
